package room_event

import (
	"bytes"
	"encoding/json"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	match_data2 "longmen/server/internal/rpc/tencentim/match_data"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/messages/pb"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/internal/services/nami/services/sports/basketball/bbcache"
	pb "longmen/server/pkg/protobuf"
	"strconv"
)

type lineupResp struct {
	Lineup string `json:"lineup"`
	Type   string `json:"type"`
}

func handlerMatch(groupId int) (ret *pb.CallbackResp, err error) {

	historyMsg := match_data2.GetMatchHistoryData(cast.ToString(groupId))
	var req string

	if len(historyMsg) > 0 {
		req = matchHistoryToJson(historyMsg)
		global.Log.Debugf("handlerMatch req2 %v", req)
	}
	return utils.CallbackOkAndExt(req, cast.ToString(groupId)), nil
}

func handlerLineupEvent(groupId int) (ret *pb.CallbackResp, err error) {

	eventMsg := bbcache.NewLineUpCache().GetEvents(groupId)

	return utils.CallbackOkAndExt(eventMsg, cast.ToString(groupId)), nil
}

func handlingIndexLive(groupId int) (ret *pb.CallbackResp, err error) {

	historyMsg := match_data2.GetIndexData(cast.ToString(groupId))
	var req string
	if len(historyMsg) > 0 {
		req = matchHistoryToJson(historyMsg)
	}
	return utils.CallbackOkAndExt(req, cast.ToString(groupId)), nil
}

func handlingLineupLive1(groupId int) (ret *pb.CallbackResp, err error) {

	historyMsg := match_data2.GetLineupData(cast.ToString(groupId))

	var resp lineupResp
	if historyMsg != nil {
		n := len(historyMsg[0])

		if n > 0 {
			lineup1 := historyMsg[0][:n/3]
			//lineup1 := historyMsg[0]
			resp.Lineup = lineup1
			resp.Type = messages2.LineupLive1MessageType
		}
	}
	if resp.Lineup == "" {
		global.Log.Debugf("查無陣容資訊, room_id: %v", strconv.Itoa(groupId))
	}
	rs := utils.CallbackOkAndExt(resp, cast.ToString(groupId))
	//global.Log.Debugf("阵容1响应:%+v", rs)
	return rs, err
}

func handlingLineupLive2(groupId int) (*pb.CallbackResp, error) {
	historyMsg := match_data2.GetLineupData(cast.ToString(groupId))
	var resp lineupResp
	if historyMsg != nil {
		n := len(historyMsg[0])

		if n > 0 {
			lineup2 := historyMsg[0][n/3 : n/3*2]
			resp.Lineup = lineup2
			resp.Type = messages2.LineupLive2MessageType
		}
	}
	rs := utils.CallbackOkAndExt(resp, cast.ToString(groupId))
	global.Log.Debugf("阵容2响应:%+v", rs)
	return rs, nil
}

func handlingLineupLive3(groupId int) (*pb.CallbackResp, error) {
	historyMsg := match_data2.GetLineupData(cast.ToString(groupId))
	var resp lineupResp
	if historyMsg != nil {

		n := len(historyMsg[0])

		if n > 0 {
			lineup3 := historyMsg[0][n/3*2:]
			resp.Lineup = lineup3
			resp.Type = messages2.LineupLive3MessageType
		}
	}
	rs := utils.CallbackOkAndExt(resp, cast.ToString(groupId))
	//global.Log.Debugf("阵容3响应:%+v", rs)
	return rs, nil
}

func handlingTextLive(groupId int) (ret *pb.CallbackResp, err error) {

	historyMsg := match_data2.GetTextLiveData(cast.ToString(groupId))
	var req string

	if len(historyMsg) > 0 {
		req = matchHistoryToJson(historyMsg)
	}
	global.Log.Debugf("文字直播大小:%v,groupId:%d", len(req), groupId)
	return utils.CallbackOkAndExt(req, cast.ToString(groupId)), nil
}

//protobuf返回
func handlingTextLivePb(groupId int) (ret *pb.CallbackResp, err error) {
	historyMsg, b := match_data2.GetTextLive(cast.ToString(groupId))
	global.Log.Debugf("原始直播大小:%+vKB", len(historyMsg)/1000)
	if !b {
		return
	}
	resp := &protobuf.SentMessageResp{}
	var textLiveMessage *messages2.RoomTextLiveMessage
	json.Unmarshal([]byte(historyMsg), &textLiveMessage)
	resp.Type = textLiveMessage.Type
	var textData []*protobuf.TextData
	for _, v := range textLiveMessage.TextLive {
		textData = append(textData, &protobuf.TextData{
			Id:         int32(v.Id),
			Time:       v.Time,
			Type:       uint32(v.Type),
			Data:       v.Data,
			Position:   uint32(v.Position),
			Main:       uint32(v.Main),
			AwayScore:  int32(v.AwayScore),
			HomeScore:  int32(v.HomeScore),
			CreateTime: v.CreateTime,
		})
	}
	resp.TextLive = textData
	// 将 protobuf 数据序列化为字节数组
	protoData, err := utils.ToProtoData(resp)
	if err != nil {
		global.Log.Errorf("handlingTextLivePb Err:%v", err)
		return
	}
	global.Log.Debugf("文字直播PB大小:%+vKB", len(string(protoData))/1000)
	return utils.CallbackOkAndExt(protoData, cast.ToString(groupId)), nil
}

func matchHistoryToJson(jsonMsg []string) string {
	var buffer bytes.Buffer

	buffer.WriteString("[")
	for _, m := range jsonMsg {
		buffer.WriteString(m)
		buffer.WriteString(",")
	}
	buffer.Truncate(len(buffer.String()) - 1)
	buffer.WriteString("]")
	return buffer.String()
}

func lineupToJason(lineup string) string {
	var buffer bytes.Buffer

	buffer.WriteString("{\"linup\":\"")
	buffer.WriteString(lineup)
	buffer.WriteString("\"}")
	return buffer.String()
}
